package com.google.thumbseekbardemo

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.support.v7.widget.AppCompatSeekBar
import android.util.AttributeSet
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.SeekBar


/**
 * When I wrote this, only God and I understood what I was doing.
 * Now, God only knows.
 *
 *
 * Created by @Harry on 2018-08-31
 */
class XSeekBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        FrameLayout(context, attrs, defStyleAttr) {

    init {
        init(context, attrs, defStyleAttr)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        View.inflate(context, R.layout.layout_x_seekbar, this)

        val sb = findViewById<AppCompatSeekBar>(R.id.sb)

        sb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

                val bt = Button(context)
                bt.setBackgroundResource(R.drawable.shape_thumb_bg)
                bt.text = "$progress%"

                //未布局好的iew需要加这两句
                bt.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
                bt.layout(0, 0, bt.measuredWidth, bt.measuredHeight)

                val bitmap = loadBitmapFromView(bt)
                val drawable = BitmapDrawable(null, bitmap)

                val oldRect = sb.thumb.bounds//获取原来的Bounds构建一个Rect
                drawable.bounds = oldRect//为新的图片对象添加Bounds
                sb.thumb = drawable//设置新的图片

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
        })

    }

    private fun loadBitmapFromView(v: View): Bitmap {

        val w = v.width

        val h = v.height

        val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)

        val c = Canvas(bmp)

        c.drawColor(Color.WHITE)

        /** 如果不设置canvas画布为白色，则生成透明  */

        v.layout(0, 0, w, h)

        v.draw(c)

        return bmp

    }
}
